package com.order.service.impl;

import com.alibaba.nacos.client.naming.utils.ThreadLocalRandom;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.order.dto.UserDto;
import com.order.mapper.OrderMapper;
import com.order.pojo.Order;
import com.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.List;
import java.util.UUID;


/**
 * @author Administrator
 */
@Service
public class OderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;

    /**
     *
     * @param productId
     * @param userId
     * @return
     */
    public Order makeOder(Long productId, Long userId) {

        List<ServiceInstance> instances=discoveryClient.getInstances("user-service");
        //负载均衡
        int rangomIndex = ThreadLocalRandom.current().nextInt(instances.size());
        ServiceInstance serviceInstance=instances.get(rangomIndex);
        System.out.println("获取到的服务=="+serviceInstance.getUri()+",端口号为-->"+serviceInstance.getPort());
        //String userServieURL=serviceInstance.getUri().toString()+"/user/user?id="+userId;
        //随机获取user信息
        String userServieURL="http://"+serviceInstance.getServiceId().toString()+"/user/user?id="+(rangomIndex+userId);
        //username 从user服务获取
        //服务路径
       // String userServieURL="http://localhost:8088/user/user?id="+userId;
        //调用服务
        UserDto userDto=restTemplate.getForObject(userServieURL,UserDto.class);
        System.out.println("userDto="+userDto);
        Order order=Order.builder()
                .createTime(new Date())
                .img("aaaa.jpg")
                .price(10.3)
                .ordernumber(UUID.randomUUID().toString())
                .productId(rangomIndex+userId)
                .userId(userId)
                .username(userDto.getUserName()).build();

       // orderMapper.insert(order);
        return order;
    }

    public List<Order> getOrder(Long userId) {
        Order order=Order.builder().userId(userId).build();
        QueryWrapper<Order> queryWrapper = new QueryWrapper<Order>(order);
        List<Order> list=orderMapper.selectList(queryWrapper);
        return list;
    }
}
